package com.iwjw.ibatis.plugins.dynamic.spring.aop;

import com.iwjw.ibatis.annotations.Master;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.annotation.Annotation;

/**
 * Master注解拦截器，强制使方法切换到主库
 *
 * @author: huangweiwei
 * @email: ihuangweiwei@163.com
 * @created:2016/10/28
 */
public class MasterMethodInterceptor implements MethodInterceptor {

    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        Annotation annotation = methodInvocation.getMethod().getAnnotation(Transactional.class);
        //如果开启了事务，直接执行
        if (annotation != null) {
            return methodInvocation.proceed();
        }
        annotation = methodInvocation.getMethod().getAnnotation(Master.class);
        //未使用Master注解
        if (annotation == null) {
            return methodInvocation.proceed();
        }
        try {
            //异常处理，必须切换回数据库状态
            MasterSynchronizationManager.registerMaster();
            return methodInvocation.proceed();
        } catch (Exception exception) {
            throw exception;
        } finally {
            MasterSynchronizationManager.clear();
        }
    }
}
